import type { AppContext } from '../types/index.js';
import { koaSwagger } from 'koa2-swagger-ui';
import { getSwaggerConfig } from '../config/swagger.js';

/**
 * Swagger中间件
 * 根据配置决定是否启用Swagger文档
 */
export function createSwaggerMiddleware() {
  const swaggerConfig = getSwaggerConfig();

  if (!swaggerConfig.enabled) {
    return async (ctx: AppContext, next: () => Promise<void>): Promise<void> => {
      await next();
    };
  }

  return koaSwagger({
    routePrefix: swaggerConfig.path,
    swaggerOptions: {
      spec: swaggerConfig.spec as Record<string, unknown>,
    },
    title: 'API Documentation',
    hideTopbar: true,
    customCSS: `
      .swagger-ui .topbar { display: none; }
      .swagger-ui .info { margin: 20px 0; }
      .swagger-ui .scheme-container { margin: 20px 0; }
    `,
  });
}

/**
 * 检查是否为Swagger相关路径
 */
export function isSwaggerPath(path: string): boolean {
  const swaggerConfig = getSwaggerConfig();
  return (
    path.startsWith(swaggerConfig.path) || path.includes('swagger') || path.includes('api-docs')
  );
}
